<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>球球</title>
    <style>
      .ball {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        top: 10px;
        left: 10px;
        position: absolute;
        background-color: red;
        transition: all 20ms;
      }
    </style>
  </head>
  <body>
    <div class="ball"></div>
  </body>
  <script>
    let ball = document.querySelector(".ball"),
      disX = 20,
      disY = 20,
      maxLeft = window.innerWidth - ball.clientWidth,
      maxTop = window.innerHeight - ball.clientHeight;
    setInterval(() => {
      const rect = ball.getBoundingClientRect();
      let left = rect.left + disX,
        top = rect.top + disY;
      if (left > maxLeft) {
        left = maxLeft;
        disX = -disX;
      }
      if (left < 0) {
        left = 0;
        disX = -disX;
      }
      if (top > maxTop) {
        top = maxTop;
        disY = -disY;
      }
      if (top < 0) {
        top = 0;
        disY = -disY;
      }
      ball.style.left = left + "px";
      ball.style.top = top + "px";
    }, 20);
  </script>
</html>
